package com.springmvc.service.impl;

import java.util.ArrayList;

import javax.annotation.Resource;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.springframework.stereotype.Service;

import com.base.util.PropertyUtil;
import com.springmvc.dao.IJobDao;
import com.springmvc.service.IJobService;

@Service("jobService")
public class JobServiceImpl implements IJobService {
	@Resource
	private IJobDao jobDao;
	
	//private static Repository repository;
	
	public ArrayList<com.springmvc.domain.Job> GetAll() {
		return this.jobDao.selectAll();
	}

	public Boolean ExecJobById(int parJobID) {
		com.springmvc.domain.Job curJob=this.jobDao.selectByID(Long.parseLong(String.valueOf(parJobID)));
		
		String jobName=curJob.getName();
		
		try
		{
			KettleEnvironment.init();
			//创建资源库对象
			KettleDatabaseRepository repository=new KettleDatabaseRepository();
			//获取properties配置
			String dbType=PropertyUtil.getProperty("kettle.dbType");
			String access=PropertyUtil.getProperty("kettle.access");
			String host= PropertyUtil.getProperty("kettle.host");
			String dbName= PropertyUtil.getProperty("kettle.dbName");
			String port=PropertyUtil.getProperty("kettle.port");
			String username= PropertyUtil.getProperty("kettle.username");
			String password= PropertyUtil.getProperty("kettle.password");
			//创建资源库数据库对象
			DatabaseMeta dataMeta=new DatabaseMeta("",dbType,access,host,dbName,port,username,password);
			//资源库元对象
			KettleDatabaseRepositoryMeta repMeta=new KettleDatabaseRepositoryMeta("","","",dataMeta);
			repository.init(repMeta);
			//连接资源库
			repository.connect("admin", "admin");
			
			RepositoryDirectoryInterface repDir=new RepositoryDirectory();
			repDir=repository.loadRepositoryDirectoryTree();
			
			JobMeta jobMeta=repository.loadJob(jobName,repDir,null,null);
			Job repJob=new Job(repository,jobMeta);
			
			repJob.start();
			repJob.waitUntilFinished();
			
		}
		catch(KettleException ex){
			ex.printStackTrace();
		}
		
		return true;
	}
}
